<template>
	<mt-actionsheet v-model="sheetVisible" :actions="actions">
	</mt-actionsheet>
</template>

<script>
	export default {
		name: 'choose-image',
		props: {
			filter: {
				type: String,
				default: 'image'
			},
			maximum: {
				type: Number,
				default: 4,
			},
			// 是否支持多选图片
			multiple: {
				type: Boolean,
				default: true,
			},
			// 是否使用系统相册文件选择界面
			system: {
				type: Boolean,
				default: false,
			},
			chooseImage: {
				type: Function,
				require: true
			}
		},
		data() {
			return {
				sheetVisible: false,
				count: 0,
				actions: [{
						name: '拍照',
						method: this.cameraImg
					},
					{
						name: '从相册中选择',
						method: this.galleryImg
					}
				],
				compressImages:[],
				selectMethod: '',
				selectImg: []
			}
		},
		watch: {
			selectImg: {
				handler(to, from) {

					if(this.selectMethod == 'cameraImg') {
						if(to.length == 1) {
							this.chooseImage(this.selectImg)
							this.selectImg = [];
							this.compressImages = [];
							this.count = 0;
						}
					} else if(this.selectMethod == 'galleryImg') {
						if(this.multiple) {
							if(to.length == this.count && to.length > 0) {
								this.chooseImage(this.selectImg)
							this.compressImages = [];
								this.selectImg = [];
								this.count = 0;
							}
						} else {
							if(to.length == this.count && to.length > 0) {
								this.chooseImage(this.selectImg)
							this.compressImages = [];
								this.selectImg = [];
								this.count = 0;
							}
						}
					}
				},
				deep: true
			}
		},
		methods: {
			//超过最多选择图片数量事件 
			onmaxed() {

			},
			show() {
				this.sheetVisible = true;
			},
			// 从相册中选择
			galleryImg() {
				this.selectMethod = "galleryImg"
				var galleryOptions = {
					filter: this.filter,
					system: this.system,
					multiple: this.multiple,
				}
				if(this.multiple) {
					galleryOptions.maximum = this.maximum;
				}
				plus.gallery.pick(this.galleryImgsuccesCB, this.galleryImgerrorCB, galleryOptions)
			},
			// 从相册中选择 照片成功后回调
			galleryImgsuccesCB(e) {
				var files = null;
				if(typeof e == "string") {
					files = [e]
				} else {
					files = e.files
				}
				this.count = files.length;
				for(var i = 0; i < files.length; i++) {
					this.compressImages.push({filePath: files[i],isNeedCompress: true})
				}
				console.log('this.compressImages')
				console.log(this.compressImages)
//				return
				this.getMetadata(this.compressImages[0].filePath,0);
			},
			// 从相册中选择图片失败后回调
			galleryImgerrorCB() {
			},
			// 获取图片大小
			getMetadata(filePath, filePathIndex) {
				
				var _this = this;
				plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
						entry.getMetadata(function(metaData) {
								console.log('getMetadata')
								if(metaData.size > 5 * 1000) {
//									
									_this.chooseCompressImageObject()
								} else {
									_this.compressImages[filePathIndex].isNeedCompress = false;
									// 直接读取并转换base64
									_this.resolveLocalFileSystemURL(filePath);
								}
							},
							function() {
								alert("获取失败")
							});
					},
					function(error) {
						console.log('resolveLocalFileSystemURL  +  error')
						console.log(error)
					})
			},
			chooseCompressImageObject() {
				var needCompressImagesIndex = this.compressImages.findIndex(function(item) {
					return item.isNeedCompress
				});
				console.log("needCompressImagesIndex")
				console.log(needCompressImagesIndex)
				if(needCompressImagesIndex >= 0) {
					this.compressImage(this.compressImages[needCompressImagesIndex].filePath, needCompressImagesIndex)
				}
			},
			//压缩图片
			compressImage(filePath, needCompressImagesIndex) {
				console.log("compressImage")
				console.log(needCompressImagesIndex)
				console.log(filePath)
				
				var _this = this;
				if(filePath.indexOf('file://') >= 0) {
					var newfilePath = filePath.replace('file://', '');
					newfilePath = plus.io.convertAbsoluteFileSystem(newfilePath);
				}
				// 拼接压缩后图片的路径
				var dstPath = newfilePath.substring(0, newfilePath.lastIndexOf('.')) +
					'_compress' +
					newfilePath.substring(newfilePath.lastIndexOf('.'));
				plus.zip.compressImage({
					src: filePath,
					dst: dstPath,
					quality: 30,
					width: '720px',
					height: 'auto'
				}, function() {
					console.log("我进到压缩文件里面了")
					_this.compressImages[needCompressImagesIndex].isNeedCompress = false;
					_this.resolveLocalFileSystemURL(dstPath, true);
					_this.chooseCompressImageObject();
				},function(err){

					console.log('err')
					console.log(err)
					alert("压缩图片失败")
				})
			},
			// 读取图片并转换成base64
			resolveLocalFileSystemURL(dstPath, isCompressImage) {
				var _this = this;
				console.log("resolveLocalFileSystemURL")
				plus.io.resolveLocalFileSystemURL(dstPath, function(entry) {
					console.log("plus.io.resolveLocalFileSystemURL")

					entry.file(function(file) {
						var reader = new plus.io.FileReader();
						reader.readAsDataURL(file);
						reader.onloadend = function(e) {
							// 删除缓存图片
							entry.remove();
							var LocalURL = entry.toLocalURL();
							_this.selectImg.push({
								filePath: LocalURL,
								dataBase64: e.target.result
							});
							console.log(_this.selectImg)
						};
					});
				}, function(err) {
					plus.nativeUI.alert('图片无法打开，请重新选择');
				})
			},
			// 拍照
			cameraImg() {

				//				console.log('cameraImg')
				// 获取设备默认的摄像头对象 
				var _this = this;
				var cmr = plus.camera.getCamera();
				var resList = cmr.supportedImageResolutions;
				var fmt = cmr.supportedImageFormats[0];
				var res = resList[0];
				this.selectMethod = "cameraImg";
				for(var i = resList.length - 1; i >= 0; i--) {
					var item = resList[i];
					var arr = item.split('*');
					if(arr && arr.length == 2 && arr[0] == 1280 && arr[1] == 720) {
						res = item;
					}
				}
				cmr.captureImage(function(path) {
					_this.getMetadata(path);
				}, function(err) {

				}, {
					resolution: res,
					format: fmt
				});
			}
		}
	}
</script>

<style lang="scss">
	.mint-actionsheet {
		.mint-actionsheet-list {
			.mint-actionsheet-listitem {
				height: 90px;
				line-height: 90px;
				font-size: 30px;
			}
		}
		.mint-actionsheet-button {
			height: 90px;
			line-height: 90px;
			font-size: 30px;
		}
	}
</style>